/**
 * Created by Delicate on 2018/1/3.
 */
import React from 'react';
import {
    StyleSheet,
    View,
    ScrollView,
    DeviceEventEmitter
} from 'react-native';

import NavBar from '../../components/NavBarView'

import {
    FormEvent,
    FormStatus,
    PassportField,
    SubmitBtn
} from '../../components/Form'
import Constants from '../../config/Constants'
import PassportService from '../../services/Passport'

let _self = null;
let _timer = null;

const validRule = {
    form: {
        login_name: {
            required: true,
            regExp: /1\d{10}/,
            errorMsg: '您输入的手机号码格式有误'
        },
        mobileCode: {
            required: true,
            regExp: /\d{6}/,
            errorMsg: '请输入6位数字手机验证码'
        },
        institutionName: {
            required: true,
        },
        busniessNumber: {
            required: true,
            regExp: /^[0-9A-Za-z]{18,18}$/,
            errorMsg: '请输入18位营业执照号'
        },
        password: {
            required: true,
            regExp: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$/,
            errorMsg: '请输入6-20位数字字母组合密码'
        }
    },
    formUn: {
        login_name: {
            required: true,
            regExp: /1\d{10}/,
            errorMsg: '您输入的手机号码格式有误'
        },
        mobileCode: {
            required: true,
            regExp: /\d{6}/,
            errorMsg: '请输入6位数字手机验证码'
        },
        password: {
            required: true,
            regExp: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$/,
            errorMsg: '请输入6-20位数字字母组合密码'
        }
    }
}

class Views extends React.Component {

    constructor(props) {
        super(props)
        _self = this;
        this.state = {
            formStatus: FormStatus.EDIT,
            form: {
                login_name: '',
                mobileCode: '',
                institutionName: '',
                busniessNumber: '',
                password: ''
            },
            isAuth: false,
            sendText: '',
            canSend: true
        }
    }

    componentWillMount() {

    }

    componentDidMount() {

    }

    componentWillUnmount() {
        clearInterval(_timer);
    }

    async forgot() {
        const valid = FormEvent.isValid(_self.state.isAuth ? validRule.form : validRule.formUn, _self.state.form);
        if (valid.result) {
            _self.setState({
                formStatus: FormStatus.SUBMITTING
            });
            const {result, message} = await PassportService.forgot({
                params: {
                    ..._self.state.form,
                    type: _self.state.isAuth ? '02' : '01'
                }
            });
            if (result) {
                DeviceEventEmitter.emit(Constants.LISTENER_LOGGING);
                _self.props.navigation.goBack();
            }
            Toast.show(message);
            _self.formReset();
        } else {
            Toast.show(valid.message);
        }
    }

    //发送事件
    async send() {
        //判断是否可以发送
        if (_self.state.canSend) {
            //重置倒计时
            let times = Constants.SMS_INTERVAL;
            clearInterval(_timer);
            //校验注册电话
            const login_name = _self.state.form.login_name;
            if (validRule.form.login_name.regExp.test(login_name)) {
                //禁用发送事件
                _self.setState({canSend: false});
                //异步发送事件
                const {result, message, data} = await PassportService.forgotSend({params: {login_name}});
                if (result) {

                    _self.setState({
                        isAuth: data.auth
                    });
                    //倒计时
                    _timer = setInterval(() => {
                        times--;
                        if (times > 0) {
                            _self.setState({
                                sendText: times + '秒'
                            })
                        } else {
                            //倒计时结束 恢复发送事件并清空sendText
                            _self.setState({
                                sendText: '',
                                canSend: true
                            })
                        }
                    }, 1000);
                } else {
                    //恢复发送事件并toast
                    _self.setState({canSend: true});
                    Toast.show(message);
                }
            } else {
                Toast.show(validRule.form.login_name.errorMsg);
            }
        }
    }

    //input改变触发
    inputChange(key, value) {
        let form = _self.state.form;
        form[key] = value;
        _self.setState({form}, () => {
            if (_self.state.formStatus !== FormEvent.isCompleted(_self.state.isAuth ? validRule.form : validRule.formUn, _self.state.form)) {
                _self.setState({
                    formStatus: FormEvent.isCompleted(_self.state.isAuth ? validRule.form : validRule.formUn, _self.state.form)
                })
            }
        });
    }

    //重置表单
    formReset() {
        const form = {
            login_name: '',
            mobileCode: '',
            institutionName: '',
            busniessNumber: '',
            password: ''
        };
        _self.setState({formStatus: FormStatus.EDIT, form, isAuth: false})
    }

    render() {
        return (
            <View style={base.baseOuter}>
                <NavBar host={this} title="找回密码"/>
                <ScrollView style={styles.container}>
                    <PassportField
                        inputValue={this.state.form.login_name}
                        control={this.state.formStatus}
                        maxLength={11}
                        onChangeText={(text) => this.inputChange('login_name', text)}
                        placeholder="请输入手机号码"
                        icon={require('../../sources/icon_passport_phone.png')}/>
                    <PassportField
                        inputValue={this.state.form.mobileCode}
                        control={this.state.formStatus}
                        maxLength={6}
                        rightBtnEvent={() => this.state.canSend ? this.send() : {}}
                        rightBtnText={this.state.sendText || '获取验证码'}
                        rightBtnShow={true}
                        rightBtnTextStyle={{
                            color: this.state.canSend ? layout.MAIN_COLOR : layout.FORM_AUX_FONT_COLOR
                        }}
                        placeholder="请输入短信验证码"
                        onChangeText={(text) => this.inputChange('mobileCode', text)}
                        icon={require('../../sources/icon_passport_valid.png')}/>
                    {
                        this.state.isAuth ?
                            <View>
                                <PassportField
                                    inputValue={this.state.form.institutionName}
                                    control={this.state.formStatus}
                                    maxLength={50}
                                    placeholder="请输入企业全称"
                                    onChangeText={(text) => this.inputChange('institutionName', text)}
                                    icon={require('../../sources/icon_passport_company.png')}/>
                                <PassportField
                                    inputValue={this.state.form.busniessNumber}
                                    control={this.state.formStatus}
                                    maxLength={18}
                                    placeholder="请输入营业执照号"
                                    onChangeText={(text) => this.inputChange('busniessNumber', text)}
                                    icon={require('../../sources/icon_passport_licence.png')}/>
                            </View> :
                            <View/>
                    }
                    <PassportField
                        inputValue={this.state.form.password}
                        control={this.state.formStatus}
                        maxLength={20}
                        secureTextEntry={true}
                        onChangeText={(text) => this.inputChange('password', text)}
                        placeholder="请设置6-20位数字字母组合密码"
                        icon={require('../../sources/icon_passport_password.png')}/>
                    <SubmitBtn
                        control={this.state.formStatus}
                        text="确认"
                        onPress={() => this.forgot()}/>
                </ScrollView>
            </View>
        )
    }
}

const styles = StyleSheet.create({
    outer: {
        backgroundColor: layout.MAIN_BACKGROUND_COLOR
    },
    container: {
        flex: 1,
        width: layout.MAX_WIDTH,
        paddingHorizontal: layout.GAP_HORIZONTAL_LARGE
    }
})

//路由
const Forgot = {
    screen: Views,
    navigationOptions: {
        header: null,
    },
    name: 'Forgot',
    sign: false
};

export default Forgot;